package org.example.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.example.domain.SysDept;
import org.example.listener.DeptListener;
import org.example.service.SysDeptService;
import org.example.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Api(tags = {"部门接口"})
@RestController
@RequestMapping("sysDept")
public class SysDeptController {
    @Autowired
    SysDeptService sysDeptService;
    @ApiOperation(value = "部门查询接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功"),
            @ApiResponse(code = 600,message = "失败")
    })
    @RequestMapping("deptsList")
    public Result deptsList(){
        List<SysDept> list = sysDeptService.deptsList();
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        List<Tree<String>> treeNodes = TreeUtil.<SysDept, String>build(list, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getDeptId()+"");
                    tree.setParentId(treeNode.getParentId()+"");
                    tree.setName(treeNode.getDeptName());
                });

        return Result.success(treeNodes);
    }



    @RequestMapping("treeList")
    public List<SysDept> treeList(@RequestBody SysDept sysDept){
        List<SysDept> deptList = sysDeptService.selectlist(sysDept);
        ArrayList<SysDept> arrayList = new ArrayList<>();
        //最高层 pid=0 的
        List<SysDept> collect = deptList.stream().filter(s -> s.getParentId() == 0).collect(Collectors.toList());
        for (SysDept dept : collect) {
            arrayList.add(Recursive(deptList,dept));
        }
        return arrayList;
    }
    public SysDept Recursive(List<SysDept> list,SysDept sysDept){
        List<SysDept> arrayList = new ArrayList<>();
        for (SysDept dept : list) {
            if (dept.getParentId()!=null && dept.getParentId()==sysDept.getDeptId()){
                arrayList.add(Recursive(list,dept));
            }
        }
        if (arrayList.size()!=0){
            sysDept.setChildren(arrayList);
        }
        return sysDept;
    }

    @RequestMapping("addSave")
    public Result addSave(@RequestBody SysDept sysDept){
        boolean b =  sysDeptService.insertDept(sysDept);
        return b? Result.success(): Result.fail();
    }

    @RequestMapping("update")
    public Result update(@RequestBody SysDept sysDept){
        boolean b =  sysDeptService.updateDept(sysDept);
        return b?Result.success():Result.fail();
    }

    @RequestMapping("delete")
    public Result delete(Integer id){
        boolean b =  sysDeptService.deleteById(id);
        return b?Result.success():Result.fail();
    }

    @RequestMapping("jishu")
    public void jishu(Long deptId,Long orderNum){
        SysDept sysDept =   sysDeptService.selectByid(deptId);
        sysDept.setOrderNum(orderNum);
        sysDeptService.updateByid(deptId);
    }

//    @RequestMapping("excel")
//    public Result excel(SysDept sysDept,HttpServletResponse response){
//
//        List<SysDept> list = sysDeptService.list();
//        String simpleName = SysDept.class.getSimpleName();
//        //这里需要
//        List<DownloadData> data = list.stream().map(DownloadData::new).collect(Collectors.toList());
//        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setCharacterEncoding("utf-8");
//        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
//        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//        EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(data());
//    }



    @RequestMapping("uploadtree")
    public Result uploadtree(MultipartFile file) throws IOException {
        HashMap<String, Object> map = new HashMap<>();

        try {
            map.put("code",200);
            EasyExcel.read(file.getInputStream(),SysDept.class,new DeptListener(sysDeptService)).sheet().doRead();
        } catch (IOException e) {
            map.put("code",500);
            e.printStackTrace();
        }

        return Result.success(map);


    }
}
